package com.heima.media.task;

import com.heima.media.entity.WmNews;
import com.heima.media.service.IAuditService;
import com.heima.media.service.IWmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.redisson.client.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author: itheima
 * @create: 2022-05-19 14:46
 */
@Async
@Slf4j
@Component
public class MediaTask {


    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private IAuditService auditService;

    @Autowired
    private IWmNewsService wmNewsService;


    /**
     * 监听器逻辑，接收到消息（延迟发布文章ID）后，完成文章发布
     */
    public void handlerMsg() {
        try {
            RBlockingDeque<String> blockingDeque = redissonClient.getBlockingDeque("article-publish");
            RDelayedQueue<String> delayedQueue = redissonClient.getDelayedQueue(blockingDeque);
            //发送测试消息
            delayedQueue.offer("init", 1, TimeUnit.SECONDS);
            while (true){
                String data = blockingDeque.poll(30, TimeUnit.SECONDS);
                System.out.println("监听到延迟消息："+data);
                if(StringUtils.isNotBlank(data) && !data.equals("init")){
                    //完成发布
                    WmNews wmNews = wmNewsService.getById(data);
                    auditService.audit(wmNews);
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
